package com.yu1996.sparseArray;

public class SparseArray {

    public static void main(String[] args) {
        //先定义一个原始的二维数组
        int[][] oriArray = new int[11][11];
//        System.out.println(oriArray[0].length);
        //给原始数据赋值
        oriArray[1][2] = 1;
        oriArray[2][3] = 2;
        oriArray[2][5] = 2;

        //遍历打印出原始数组
        System.out.println("这是原始的数组：");
        for (int[] array : oriArray) {
            for (int val : array) {
                System.out.printf("%d\t", val);
//                System.out.println();
            }
            System.out.println();
        }
        System.out.println();


        //先统计总共多少个非零的数
        int sum = 0;
        for (int[] array : oriArray) {
            for (int val : array) {
                if (val != 0) {
                    sum++;
                }
            }
        }


        //将二维数组转换成稀疏数组
        //先定义一个稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = oriArray.length;
        sparseArray[0][1] = oriArray[0].length;
        sparseArray[0][2] = sum;

        //初始化稀疏数组（将非零的数存入稀疏数组）
        int count = 1;
        for (int i = 0; i < oriArray.length; i++) {
            for (int j = 0; j < oriArray[0].length; j++) {
                if (oriArray[i][j] != 0) {
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = oriArray[i][j];
                    count++;
                }
            }
        }

        System.out.println();
        //打印出稀疏数组
        System.out.println("这是存入的稀疏数组：");
        for (int i = 0; i < sparseArray.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
        }


        //根据稀疏数组还原原始数据
        int[][] resArray = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            resArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }


        System.out.println();
        //遍历打印出原始数据
        System.out.println("这是转换之后的数据：");
        for (int[] array : resArray) {
            for (int val : array) {
                System.out.printf("%d\t", val);
            }
            System.out.println();
        }
        System.out.println();


    }
}
